package com.example;

import javafx.scene.image.PixelFormat;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

/**
 * <p>图像转换</p>
 *
 * @author dc
 * @date 2025-09-25
 **/
public class ImageConverter {
    static {
        nu.pattern.OpenCV.loadLocally();
    }

    /**
     * 将JavaFX WriteableImage转换为OpenCV Mat
     */
    public static Mat writeableImageToMat(WritableImage image) {
        int width = (int) image.getWidth();
        int height = (int) image.getHeight();
        byte[] buffer = new byte[width * height * 4];

        PixelReader reader = image.getPixelReader();
        reader.getPixels(0,  0, width, height,
                PixelFormat.getByteBgraInstance(),
                buffer, 0, width * 4);

        Mat mat = new Mat(height, width, CvType.CV_8UC4);
        mat.put(0,  0, buffer);

        // 转换为灰度图格式（OpenCV标准）
        Mat rgbaMat = new Mat();
        Imgproc.cvtColor(mat,  rgbaMat, Imgproc.COLOR_BGR2BGRA);
        mat.release();

        return rgbaMat;
    }

    /**
     * 将OpenCV Mat转换为JavaFX WriteableImage
     */
    public static WritableImage matToWriteableImage(Mat mat) {
        Mat rgbaMat = new Mat();
        Imgproc.cvtColor(mat, rgbaMat, Imgproc.COLOR_BGR2BGRA);

        byte[] buffer = new byte[rgbaMat.cols() * rgbaMat.rows()  * 4];
        rgbaMat.get(0,  0, buffer);
        mat.release();
        System.out.println(rgbaMat.rows() + " " + rgbaMat.cols());
        WritableImage image = new WritableImage(rgbaMat.cols(),  rgbaMat.rows());
        PixelWriter writer = image.getPixelWriter();
        writer.setPixels(0,  0, rgbaMat.cols(),  rgbaMat.rows(),
                PixelFormat.getByteBgraInstance(),
                buffer, 0, rgbaMat.cols()  * 4);

        return image;
    }
}
